<template>
  <div class="file-viewer-page">
    <div class="section-title">上传的二维码</div>
    <div class="image-container" v-if="image">
      <van-image :src="image.url" fit="cover" class="preview-image" @click="showImagePreview" />
    </div>
    <div v-else class="no-data">暂无图片</div>

    <div class="section-title">上传的PDF文件</div>
    <div class="pdf-item" v-if="pdfFile">
      <van-cell :title="pdfFile.name" is-link @click="viewPdf(pdfFile.url)">
        <template #right-icon>
          <van-icon name="eye" style="margin-right: 10px;" />
          <van-icon name="down" @click.stop="downloadPdf" />
        </template>
      </van-cell>
    </div>
    <div v-else class="no-data">暂无PDF文件</div>

    <!-- 图片预览 -->
    <van-image-preview v-model:show="showPreview" :images="[image?.url || '']" />

    <!-- PDF查看器 -->
    <van-popup v-model:show="showPdfViewer" position="bottom" :style="{ height: '90%' }" @closed="clearPdfPages">
      <div class="pdf-viewer-header">
        <van-nav-bar :title="pdfFile?.name || 'PDF预览'" left-text="返回" @click-left="closePdfViewer">
          <template #right>
            <van-icon name="down" @click="downloadPdf" />
          </template>
        </van-nav-bar>
      </div>
      <div class="pdf-viewer-container">
        <div v-if="pdfLoading" class="pdf-loading">PDF加载中...</div>
        <div v-else-if="pdfPages.length > 0">
          <div v-for="(page, index) in pdfPages" :key="index" class="pdf-page">
            <img :src="page" alt="PDF页面" class="pdf-page-image" />
          </div>
        </div>
        <div v-else class="pdf-error">PDF加载失败</div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { getFilePathById } from '../../api/uploadFliePath'
// 引入PDF.js
import * as pdfjsLib from 'pdfjs-dist'
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.min?url'

// 设置PDF.js worker
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker

const route = useRoute()
const companyId = route.query.id

// 图片相关
const image = ref<{ url: string } | null>(null)
const showPreview = ref(false)

// PDF相关
const pdfFile = ref<{ name: string, url: string } | null>(null)
const showPdfViewer = ref(false)
const pdfPages = ref<Array<string>>([])
const pdfLoading = ref(false)

// 显示图片预览
const showImagePreview = () => {
  showPreview.value = true
}

// 查看PDF
const viewPdf = async (url: string) => {
  showPdfViewer.value = true
  // 渲染PDF页面
  await renderPdfPages(url)
}

// 下载PDF文件
const downloadPdf = () => {
  if (pdfFile.value) {
    // 使用window.open打开链接
    window.open(pdfFile.value.url, '_blank')

    //使用a标签下载 ,但是移动端浏览器不支持click
    // const link = document.createElement('a')
    // link.href = pdfFile.value.url
    // link.download = pdfFile.value.name
    // link.click()
  }
}

// 渲染PDF页面为图片
const renderPdfPages = async (pdfUrl: string) => {
  pdfLoading.value = true
  pdfPages.value = []

  try {
    const loadingTask = pdfjsLib.getDocument(pdfUrl)
    const pdf = await loadingTask.promise
    const pages = []

    // 渲染前几页（避免过多页面影响性能）
    const pageCount = Math.min(pdf.numPages, 10)

    for (let i = 1; i <= pageCount; i++) {
      const page = await pdf.getPage(i)
      // 根据设备屏幕调整缩放比例
      const scale = window.innerWidth < 768 ? 1.2 : 1.5
      const viewport = page.getViewport({ scale })

      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      if (!context) continue

      canvas.height = viewport.height
      canvas.width = viewport.width

      const renderContext = {
        canvasContext: context,
        viewport: viewport,
        canvas: canvas
      }

      await page.render(renderContext).promise
      pages.push(canvas.toDataURL())
    }

    pdfPages.value = pages
  } catch (error) {
    console.error('PDF渲染失败:', error)
  } finally {
    pdfLoading.value = false
  }
}

// 清除PDF页面数据
const clearPdfPages = () => {
  pdfPages.value = []
}

// 关闭PDF查看器
const closePdfViewer = () => {
  showPdfViewer.value = false
}

// 获取文件数据
const fetchFiles = async (id: any) => {
  if (!id || id === 'undefined') {
    console.warn("无效的ID参数:", id)
    return
  }

  try {
    const response: any = await getFilePathById(id)
    console.log("获取成功", response)
    const basicUrl = "http://localhost:9091"
    if (response.data) {
      // 处理单个图片
      if (response.data.image) {
        image.value = { url: basicUrl + response.data.image }
      }

      // 处理单个PDF
      if (response.data.pdf) {
        const pdfPath = response.data.pdf;
        const fileName = pdfPath.split('/').pop() || '文件.pdf';
        pdfFile.value = {
          name: fileName,
          url: basicUrl + response.data.pdf
        }
      }
    }
  } catch (err) {
    console.log("获取失败", err)
  }
}

onMounted(async () => {
  await fetchFiles(companyId)
})
</script>

<style scoped>
.file-viewer-page {
  padding: 10px;
  min-height: 100vh;
}

.section-title {
  text-align: center;
  font-weight: bold;
  background-color: #e0e0e0;
  padding: 10px;
  margin: 10px 0;
  font-size: 16px;
  width: 90vw;
}

.image-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.preview-image {
  width: 80%;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #999;
}

.pdf-viewer-header {
  position: sticky;
  top: 0;
  z-index: 10;
}

.pdf-viewer-container {
  padding: 10px;
  overflow-y: auto;
  height: calc(100% - 56px);
}

.pdf-page {
  margin-bottom: 20px;
  text-align: center;
}

.pdf-page-image {
  max-width: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.pdf-loading,
.pdf-error {
  text-align: center;
  padding: 20px;
  color: #999;
}

.pdf-error {
  color: #f44336;
}
</style>